package com.zcsy.commons.model;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @ClassName: SysContent
 * @Description: 获取用户信息，供后续线程内方法使用
 * @author <a href="mailto:tanghan@ygsoft.com"> tanghan</a>
 * @date 2015年2月3日 上午11:01:40
 * @since JDK 1.7
 */
public class RequestContext {

	private static ThreadLocal<HttpServletRequest> requestLocal = new ThreadLocal<HttpServletRequest>();
	private static ThreadLocal<HttpServletResponse> responseLocal = new ThreadLocal<HttpServletResponse>();
	
	private static final ThreadLocal<Map<String, Object>> tl = new ThreadLocal<Map<String, Object>>();

	public static HttpServletRequest getRequest() {
		return (HttpServletRequest) requestLocal.get();
	}

	public static void setRequest(HttpServletRequest request) {
		requestLocal.set(request);
	}

	public static HttpServletResponse getResponse() {
		return (HttpServletResponse) responseLocal.get();
	}

	public static void setResponse(HttpServletResponse response) {
		responseLocal.set(response);
	}

	public static HttpSession getSession() {
		return (HttpSession) ((HttpServletRequest) requestLocal.get()).getSession();
	}
	
	public static Map<String, Object> getAttributes() {
		Map<String, Object> attributes = tl.get();
		return attributes;
	}

	public static void setAttributes(Map<String, Object> attributes) {
		tl.set(attributes);
	}
	
	public static Integer getUserId() {
		Map<String, Object> attributes = RequestContext.getAttributes();
		if (attributes != null && attributes.containsKey(RequestConstants.USER_ID)) {
			return (Integer) attributes.get(RequestConstants.USER_ID);
		}
		return null;
	}
	
	
	/** 
	 * @Title: getRequestIp 
	 * @Description: 获取请求端IP地址
	 * @param @return     
	 * @return String  IP地址   
	 * @throws 
	 */
	public static String getRequestIp(){
		HttpServletRequest request = getRequest();
		String ip = request.getHeader("x-forwarded-for");   
	    if(ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) 
	    	ip = request.getHeader("Proxy-Client-IP");   
	    if(ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) 
	    	ip = request.getHeader("WL-Proxy-Client-IP");   
	    if(ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) 
	    	ip = request.getRemoteAddr();
	    if(ip != null && ip.equals("0:0:0:0:0:0:0:1")){
	    	ip = "127.0.0.1";
	    }
	    
	    return ip; 
	}
	
}
